package com.motu.monstercity.server.game.timedtask;

import com.motu.monstercity.server.game.commondata.act.Act;
import com.motu.monstercity.server.game.commondata.act.ActConstant;
import com.motu.monstercity.server.game.logic.ActConventionManager;
import com.motu.monstercity.server.game.logic.ActManager;
import com.motu.monstercity.server.game.logic.UnionMobileManager;
import com.motu.monstercity.server.game.logic.UnionScuffleManager;
import com.motu.vertx.module.utility.threadpool.DBLogManager;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class ActCloseTask implements Runnable, Delayed {

	public final static Logger logger = LoggerFactory.getLogger(ActCloseTask.class);

	private long actId;// 活动ID
	private int actType;// 活动类型
	private String  param;// 参数
	private long execTime;// 任务执行时间

	public ActCloseTask(long actId, int actType, long execTime, String param) {
		this.actId = actId;
		this.actType = actType;
		this.param = param;
		this.execTime = execTime;
	}

	@Override
	public void run() {
		JsonObject jsonObject = new JsonObject();
		jsonObject.put("actId", actId);
		jsonObject.put("actType", actType);
		jsonObject.put("param", param);
		TimedTaskManager.sendWorkTask(TimeTaskCmd.WORK_ACT_CLOSE, jsonObject);
	}

	public static void runTask(JsonObject jsonObject) {
		try {
			long actId = jsonObject.getLong("actId");
			int actType = jsonObject.getInteger("actType");
			String param = jsonObject.getString("param");
			try {
				logger.info("### close act id = " + actId + " actType = " + actType + " param = " + param);
				Act act = ActManager.getAct(actId);
				if (act == null) {
					return;
				}
				switch (act.getType()) {
					case ActConstant.ACT_TYPE_1001 -> { // 万能活动
						ActConventionManager.closeActConventionRankReward(act);
					}
					case ActConstant.ACT_TYPE_1002 -> { // 联盟总动员活动
						UnionMobileManager.closeActUnionMobileRankReward(act);
					}
					case ActConstant.ACT_TYPE_UNION_SCUFFLE -> { // 联盟扫荡
//						UnionScuffleManager.closeMatchRank(act);
					}
				}
			} catch (Exception e) {
				String errMsg = Tool.getException(e);
				logger.error(errMsg);
				DBLogManager.addServerCrashLog(actId, errMsg);
			}
		} catch (Exception e) {
			logger.error(Tool.getException(e));
		}
	}

	@Override
	public long getDelay(TimeUnit unit) {
		return unit.convert(execTime - TimeUtils.getCurTime(), TimeUnit.SECONDS);
	}

	@Override
	public int compareTo(Delayed o) {
		ActCloseTask that = (ActCloseTask) o;
		return execTime > that.execTime ? 1 : (execTime < that.execTime ? -1 : 0);
	}

	public long getActId() {
		return this.actId;
	}

	public long getExecTime() {
		return this.execTime;
	}

}
